package com.zxg.zbc.web.common.module;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;

import net.sf.ehcache.Cache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.requestcontext.parser.ParameterParser;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.zxg.util.WeixinComponent;
import com.zxg.zbc.web.common.util.SHA1;

public abstract class BaseElemePostModule {
	@Autowired
	protected HttpSession session;

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;

	@Autowired
	protected Cache baseCache;
	protected final static Logger log = LoggerFactory.getLogger("WEIXIN");

	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

	public void execute(Context context, ParameterParser params, Navigator nav) {

		try {

			String str = convertStreamToString(request.getInputStream());
			
			String postWriteDate = doExecute(context, params, nav, str);
			log.warn("will postWritDate:" + postWriteDate);
			
			if (postWriteDate == null || postWriteDate.equals("")) {
				postWriteDate = "{\"message\":\"ok\"}";	
			}
			try {
				response.getWriter().print(postWriteDate);
			} catch (IOException e) {
				log.error("error ", e);
			}
		} catch (Exception e) {
			log.error("error ", e);
		}

	}
	
	public static String convertStreamToString(InputStream is) {      
        /*  
          * To convert the InputStream to String we use the BufferedReader.readLine()  
          * method. We iterate until the BufferedReader return null which means  
          * there's no more data to read. Each line will appended to a StringBuilder  
          * and returned as String.  
          */     
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
         StringBuilder sb = new StringBuilder();      
     
         String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {      
                 sb.append(line + "\n");      
             }      
         } catch (IOException e) {      
             e.printStackTrace();      
         } finally {      
            try {      
                 is.close();      
             } catch (IOException e) {      
                 e.printStackTrace();      
             }      
         }      
     
        return sb.toString();      
     }

	public boolean isLegal(String token, String signature, String timestamp, String nonce) {
		String[] str = { token, timestamp, nonce };
		Arrays.sort(str);
		String bigStr = str[0] + str[1] + str[2];
		String reSignature = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();
		return reSignature.equalsIgnoreCase(signature);
	}

	

	protected abstract String doExecute(Context context, ParameterParser params, Navigator nav, String info);

	protected abstract WeixinComponent generateCurrentComponent();

	

}
